﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Input;
using Hardcodet.Scheduling;
using System.Windows.Threading;

namespace KnowledgeKiosk
{
	public partial class App : Application
	{
        public App()
		{
			Startup += Application_Startup;
			Exit += Application_Exit;
			UnhandledException += Application_UnhandledException;

			InitializeComponent();
		}

		private void Application_Startup(object sender, StartupEventArgs e)
		{
			if (IsRunningOutOfBrowser)
			{
				InitializeConfiguration();
#if DEBUG
				var root = new ScrollViewer();
				root.Content = new MainPage();
				RootVisual = root;
#else
				var settings = (Settings) Resources["Settings"];

				if (settings.LogEnabled)
					InitializeLogging();

				this.RootVisual = new MainPage();
				this.RootVisual.KeyUp += delegate(Object s, KeyEventArgs args)
				{
					if (args.Key == Key.F || args.Key == Key.Escape)
						Host.Content.IsFullScreen = !Host.Content.IsFullScreen;
				};

                Host.Content.FullScreenOptions = System.Windows.Interop.FullScreenOptions.StaysFullScreenWhenUnfocused;
                (RootVisual as FrameworkElement).Cursor = Cursors.None;

                InitializeFocusJob();
				
				Logger.WriteLine("Application started");
#endif
			}
			else
			{
				RootVisual = new InBrowserPage();
			}
		}

		private void InitializeConfiguration()
		{
			string myDocPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
			string configFilePath = Path.Combine(myDocPath, "KnowledgeKiosk.config");
			if (!File.Exists(configFilePath))
			{
				Settings.Default.Save(configFilePath);
			}
			Settings settings = Settings.Load(configFilePath);
			Resources.Add("Settings", settings);
		}

		private void InitializeLogging()
		{
			string myDocPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
			string logFilePath = Path.Combine(myDocPath, "KnowledgeKiosk.log");
			if (!File.Exists(logFilePath))
			{
				File.Create(logFilePath).Dispose();
			}
			Logger.FilePath = logFilePath;
		}

        private void InitializeFocusJob()
        {
            Scheduler _scheduler = new Scheduler();
            Job<Dispatcher> focusJob = new Job<Dispatcher>();
            focusJob.Data = this.RootVisual.Dispatcher;
            focusJob.Run.Every.Minutes(5);
            _scheduler.SubmitJob<Dispatcher>(focusJob, (j, d) => d.BeginInvoke(() => RegainFocus()));
        }

        private void RegainFocus()
        {
            Host.Content.IsFullScreen = true;
        }

		private void Application_Exit(object sender, EventArgs e)
		{
			Logger.WriteLine("Application stopped");
		}

		private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
		{
			if (!Debugger.IsAttached)
			{
				e.Handled = true;
				//Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
			}
			Logger.WriteLine(e.ExceptionObject);
		}

		private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
		{
			try
			{
				string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
				errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

				HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
			}
			catch (Exception)
			{
			}
		}
	}
}